package cn.yhjz.platform.system.controller;

import cn.yhjz.common.AjaxResponse;
import cn.yhjz.common.util.IdUtil;
import cn.yhjz.platform.system.constant.Constant;
import cn.yhjz.platform.system.entity.SysUser;
import cn.yhjz.platform.system.service.ISysUserService;
import cn.yhjz.platform.system.util.LoginUtil;
import cn.yhjz.platform.system.vo.SysUserVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 用户管理
 */
@RestController
@RequestMapping("/system/sysUser")
@PreAuthorize("hasAuthority('system:user')")
public class SysUserController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 新增或更新用户
     *
     * @param sysUser
     * @return
     */
    @PostMapping("saveOrUpdate")
    public AjaxResponse saveOrUpdate(@RequestBody SysUser sysUser) {
        if (null == sysUser.getId()) {
            sysUser.setUserCode(IdUtil.generate());
        }
        //不可以修改用户的密码，密码需要用户自己在个人中心修改
        //加密密码
        //sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        if (null == sysUser.getId()) {
            sysUser.setPassword(passwordEncoder.encode(Constant.DEFAULT_PASSWORD));
            sysUser.setCreatedBy(LoginUtil.getCurrentUser().getUserCode());
            sysUser.setCreatedTime(new Date());
            sysUserService.insert(sysUser);
        } else {
            sysUser.setUpdatedBy(LoginUtil.getCurrentUser().getUserCode());
            sysUser.setUpdatedTime(new Date());
            sysUserService.updateUserInfoById(sysUser);
        }
        return AjaxResponse.success("操作成功");
    }

    /**
     * 获得用户列表
     *
     * @return
     */
    @RequestMapping("/query")
    public AjaxResponse query(@RequestBody SysUser sysUser) {
        SysUser param = new SysUser();
        param.setUsername(sysUser.getUsername());
        List<SysUserVo> resList = sysUserService.selectVo(param);
        return AjaxResponse.success(resList);
    }

    /**
     * 删除一个用户，同时删除此用户上的角色关联
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteById")
    public AjaxResponse deleteById(Long id) {
        sysUserService.deleteById(id);
        return AjaxResponse.success();
    }

    /**
     * 还原密码
     *
     * @param userId
     * @return
     */
    @PostMapping("/resetPassword")
    public AjaxResponse resetPassword(Long userId) {
        String encodePassword = passwordEncoder.encode(Constant.DEFAULT_PASSWORD);
        sysUserService.resetPassword(userId, encodePassword);
        return AjaxResponse.success("密码还原成功");
    }
}
